package com.ctyon.watchmanager.ui.fragment;

import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.ctyon.common.event.AddWatch;
import com.ctyon.common.util.DataUtil;
import com.ctyon.common.util.TSnackbarUtil;
import com.ctyon.netlibrary.net.revert.BaseResponseEntity;
import com.ctyon.netlibrary.use.BaseObserver;
import com.ctyon.watchmanager.BasicApp;
import com.ctyon.watchmanager.R;
import com.ctyon.watchmanager.bean.AddBean;
import com.ctyon.watchmanager.bean.ContactBean;
import com.ctyon.watchmanager.databinding.FragmentAddWatchInputBinding;
import com.ctyon.watchmanager.databinding.FragmentContactsAddBinding;
import com.ctyon.watchmanager.model.net.service.NetService;
import com.ctyon.watchmanager.present.AddInputPresenter;
import com.ctyon.watchmanager.present.ContactsAddPresenter;
import com.ctyon.watchmanager.ui.BaseFragment;
import com.orhanobut.logger.Logger;

import org.greenrobot.eventbus.EventBus;

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.databinding.DataBindingUtil;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.schedulers.Schedulers;

/**
 * CreateDate：19-6-25 on 上午9:14
 * Describe:
 * Coder: lee
 */
public class ContactsAddFragment extends BaseFragment {

    public static final String TAG = "ContactsAddFragment";
    public static final String NICK = "nick";
    public static final String NUMBER = "number";

    private FragmentContactsAddBinding mBinding;
    private ContactBean contactBean;

    private List<ContactBean> contactList = new ArrayList<>();

    public static ContactsAddFragment newInstance(String nick, String number) {
        final ContactsAddFragment fragment = new ContactsAddFragment();
        final Bundle args = new Bundle();
        args.putString(NICK, nick);
        args.putString(NUMBER, number);
        fragment.setArguments(args);
        return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

        mBinding = DataBindingUtil.inflate(inflater, R.layout.fragment_contacts_add, container, false);

        return mBinding.getRoot();

    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        String nick = getArguments().getString(NICK);
        String number = getArguments().getString(NUMBER);
        Logger.t(LTAG).d("nick = " + nick + "  number = " + number);
        contactBean = new ContactBean();
        if (!DataUtil.isEmptyOr(nick, number)) {
            contactBean.setName(nick);
            contactBean.setNumber(number);
        }
        mBinding.setContactAddPresenter(contactsAddPresenter);
        mBinding.editNick.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Logger.t(LTAG).d("afterTextChanged" + "  s = " + s);
                if (null != s) {
                    mBinding.editNick.setSelection(s.toString().length());
                }
            }
        });
        mBinding.editNumber.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                Logger.t(LTAG).d("afterTextChanged" + "  s = " + s);
                if (null != s) {
                    mBinding.editNumber.setSelection(s.toString().length());
                }
            }
        });
        loadContactsE();
    }

    @Override
    public void onResume() {
        super.onResume();
        mBinding.setContactBean(contactBean);
    }

    private final ContactsAddPresenter contactsAddPresenter = () -> {
        String nick = contactBean.getName();
        String number = contactBean.getNumber();
        if (DataUtil.isEmptyOr(nick, number)) {
            TSnackbarUtil.TSBError(getActivity(), "昵称或号码有误");
            return;
        }
        uploadContacts();

    };

    @Override
    public void onDestroy() {
        super.onDestroy();
        Logger.t(LTAG).d("onDestroy");
    }

    private void loadContactsE() {
        BasicApp.getInstance().getAppExecutors().networkIO().execute(() -> {
            String contactsStr = BasicApp.getInstance().getWatch().getContacts();
            contactList.clear();
            if (!DataUtil.isEmptyAnd(contactsStr) && contactsStr.contains("&")) {
                String[] strings = contactsStr.split("&");
                ContactBean contactBean = null;
                for (int i = 0; i < strings.length; i++) {
                    if (i % 2 == 0) {
                        contactBean = new ContactBean();
                        contactBean.setNumber(strings[i]);
                    } else {
                        contactBean.setName(DataUtil.unicode2String(strings[i]));
                        contactList.add(contactBean);
                    }
                }
            }
        });

    }

    private void uploadContacts() {
        final StringBuilder contactsData = new StringBuilder();
        if (contactList.size() > 4) {
            TSnackbarUtil.TSBError(getActivity(), "最多只能保存5个联系人, 当前已保存" + contactList.size() + "人");
            return;
        }
        contactList.add(contactBean);
        Logger.t(LTAG).d("contactList size = " + contactList.size());
        for (int i = 0; i < contactList.size(); i++) {
            if (i > 0) {
                contactsData.append("&");
            }
            contactsData.append(contactList.get(i).toString());
        }
        String data = contactsData.toString().replace(" ", "");
        Logger.t(LTAG).d("contactsData : " + data);
        final String method = "contacts";
        if (NetService.getInstance().isDisable(method)) {
            TSnackbarUtil.TSBError(getActivity(), "请稍候...");
            return;
        }
        NetService.getInstance()
                .method(method)
                .contacts(BasicApp.getInstance().getManager().getManagerId(), BasicApp.getInstance().getWatch().getMeid(), data)
                .timeout(10, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserver<BaseResponseEntity>() {
                    @Override
                    public void onSuccess(BaseResponseEntity responseEntity) {
                        Logger.d("onSuccess : " + responseEntity.toString());
                        TSnackbarUtil.TSBSuccess(getActivity(), "添加成功");
                        BasicApp.getInstance().getWatch().setContacts(data);
                        contactBean.setName("");
                        contactBean.setNumber("");
                        getActivity().finish();
//                        mBinding.setContactBean(contactBean);
                    }

                    @Override
                    public String onOver() {
                        loadContactsE();
                        return method;
                    }
                });
    }

}
